set(ROOT_DIR ${CMAKE_CURRENT_SOURCE_DIR})
set(SRC_DIR ${ROOT_DIR}/src)
set(COMMON_DIR ${ROOT_DIR}/common)
set(protobuf_ROOT "/usr/local")
set(gRPC_ROOT "/usr/local")
set(abseil_ROOT "/usr/local")
set(3fs_ROOT "${ROOT_DIR}/3FS/build/src/lib/api")
set(COMMON_DIR ${ROOT_DIR}/common)

# 设置存储后端
set(FS_STRATEGY "POSIX" CACHE STRING "Select filesystem strategy: [POSIX|THREEFS|...]")
set_property(CACHE FS_STRATEGY PROPERTY STRINGS POSIX THREEFS)

if(FS_STRATEGY STREQUAL "THREEFS")
    add_compile_definitions(USE_THREEFS)
elseif(FS_STRATEGY STREQUAL "POSIX")
    add_compile_definitions(USE_POSIX)
elseif(FS_STRATEGY STREQUAL "LUSTRE")
    add_compile_definitions(USE_LUSTRE)
endif()

if (BUILD_TEST)
    add_compile_definitions(IGNORE_PYBIND)
endif()



# 添加子模块（确保子目录的CMakeLists.txt正确配置）
add_subdirectory(kvcache-service)
add_subdirectory(kvcache-sdk)
add_subdirectory(kvcache-memorypool)
add_subdirectory(kvcache-storage-client)
add_subdirectory(common)
add_subdirectory(worker-tools)
add_subdirectory(kvcache-publisher)

# 添加测试模块
# if (BUILD_TEST)
#     add_subdirectory(test)
# endif()

# 主程序配置
add_executable(kvclient main.cpp)
target_include_directories(kvclient PRIVATE
    ${ROOT_DIR}/kvcache-memorypool/include
    ${COMMON_DIR}/include
)

if (DEVICE STREQUAL "GPU")
    target_include_directories(kvclient PRIVATE
            ${CUDA_DIR}/include
    )
endif()

# 链接依赖库
target_link_libraries(kvclient PRIVATE
        kvcache_service
        kvcache_memorypool
        kv_storage_client
        common_lib
        proto-objects
        gRPC::grpc++
        gRPC::grpc++_reflection
        absl::base
        absl::log_internal_check_op
        Threads::Threads
)

if (DEVICE STREQUAL "GPU")
    target_link_libraries(kvclient PRIVATE
            CUDA::cudart
    )
endif()

if(DYNAMO)
    # 编译dynamo_adapter
    set(RUST_PROJECT_DIR ${CMAKE_CURRENT_SOURCE_DIR}/kvcache-publisher/dynamo_adapter)
    add_custom_target(build_dynamo ALL
        COMMAND cbindgen --config ${RUST_PROJECT_DIR}/cbindgen.toml --crate dynamo_adapter --output ${RUST_PROJECT_DIR}/c++include/dynamo_adapter.h
        COMMAND cargo build --manifest-path ${RUST_PROJECT_DIR}/Cargo.toml --release
        WORKING_DIRECTORY ${RUST_PROJECT_DIR}
    )
    add_library(dynamo_adapter_interface INTERFACE)
    target_include_directories(dynamo_adapter_interface INTERFACE ${RUST_PROJECT_DIR}/c++include)
    target_link_libraries(dynamo_adapter_interface INTERFACE ${RUST_PROJECT_DIR}/target/release/libdynamo_adapter.a)
    add_dependencies(dynamo_adapter_interface build_dynamo)
    target_link_libraries(kvclient PRIVATE dynamo_adapter_interface)
    add_dependencies(kvclient build_dynamo)
endif()

if(FS_STRATEGY STREQUAL "THREEFS")
    target_link_libraries(kvclient PRIVATE
            ${3fs_ROOT}/libhf3fs_api_shared.so
    )
endif()